﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Text;

namespace Asion.VSIX.Code.Create.Core
{
    /// <summary>
    /// c# 语法解析工具
    /// </summary>
    public class CSharpSyntaxUtils
    {

        /// <summary>
        /// 解析接口模版
        /// <para>默认只会解析文件中的一个class</para>
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        public static ClassGenerative ParseInterfaces(string template)
        {
            var reponse = new ClassGenerative();
            //获取编译根节点。 创建树并检索树的根节点
            SyntaxTree tree = CSharpSyntaxTree.ParseText(template);
            CompilationUnitSyntax root = tree.GetCompilationUnitRoot();

            //root.Members 是成员数 ，这个应该是namespace 起步的
            //root.Usings 是引用的命名空间
            foreach (UsingDirectiveSyntax element in root.Usings)
                Console.WriteLine($"\t{element.Name}");

            //然后获得第一个成员 也就是获得第一个Namespace
            MemberDeclarationSyntax firstMember = root.Members[0];
            var helloWorldDeclaration = (NamespaceDeclarationSyntax)firstMember;

            reponse.NameSpaceName = helloWorldDeclaration.Name.ToString();


            //从Namespace中获取Class
            var programDeclaration = (InterfaceDeclarationSyntax)helloWorldDeclaration.Members[0];


            reponse.ClassName = programDeclaration.Identifier.ValueText;


            var methods = new List<MethodGenerative>();

            foreach (var methodMember in programDeclaration.Members)
            {

                var mainDeclaration = (MethodDeclarationSyntax)methodMember;
                var methodItem = new MethodGenerative()
                {
                    MethodName = mainDeclaration.Identifier.ValueText,
                };
                string returnType = mainDeclaration.ReturnType.ToString();
                var isTaskReturnType = IsTaskReturnType(mainDeclaration);
                if (isTaskReturnType)
                {
                    //将task中的放回值拿出来
                    //这种判断是直接retun Task
                    if (!mainDeclaration.ReturnType.IsKind(SyntaxKind.IdentifierName))
                    {
                        var genericName = (GenericNameSyntax)mainDeclaration.ReturnType;
                        var argument = genericName.TypeArgumentList.Arguments[0];
                        returnType = argument.GetText().ToString();
                    }
                    else
                    {
                        returnType = string.Empty;
                    }

                }

                methodItem.SetReturnType(returnType);
                if (mainDeclaration.ParameterList.Parameters.Any())
                {
                    foreach (ParameterSyntax paramterItem in mainDeclaration.ParameterList.Parameters)
                    {
                        methodItem.Parameters.Add(new ParameterGenerative()
                        {
                            ParameterName = paramterItem.Identifier.ValueText,
                            ParameterType = paramterItem.Type.ToString()
                        });
                    }
                }
                else
                {
                    reponse.AddUsingPackage(PackageConsts.GOOGLE_PROTOBUF_WELLKNOWNTYPES);
                }

                methods.Add(methodItem);
            }
            reponse.Methods = methods;
            return reponse;
        }




        /// <summary>
        /// 判断是不是task retunType
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        private static bool IsTaskReturnType(MethodDeclarationSyntax method)
        {
            // 获取返回类型
            var returnType = method.ReturnType;
            if (returnType == null) return false; // 没有返回类型的情况

            // 检查是否为Task或Task<T>
            if (returnType.IsKind(SyntaxKind.GenericName))
            {

                var genericName = (GenericNameSyntax)returnType;
                if (genericName.Identifier.ValueText == "Task")
                {
                    return true; // 是Task<T>
                }
            }
            else if (returnType.IsKind(SyntaxKind.IdentifierName))
            {
                var identifierName = (IdentifierNameSyntax)returnType;
                if (identifierName.Identifier.ValueText == "Task")
                {
                    return true; // 是Task
                }
            }
            return false; // 不是Task或Task<T>
        }
    }
}
